package com.gxa.service.impl;

import com.gxa.common.*;
import com.gxa.common.exception.CustomerException;
import com.gxa.mapper.*;
import com.gxa.pojo.*;
import com.gxa.service.ContactService;
import com.gxa.service.CustomerService;
import com.gxa.service.RecycleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 还差客户自动剩余保护期功能，多线程
 */
@Service
public class CustomerServiceImpl implements CustomerService {
    @Autowired(required = false)
    CustomerMapper customerMapper;

    @Autowired(required = false)
    CustomerPoolMapper customerPoolMapper;

    @Autowired(required = false)
    CustomerEmployeeMapper customerEmployeeMapper;

    @Autowired(required = false)
    CustomerRecordsMapper customerRecordsMapper;

    @Autowired(required = false)
    ContactMapper contactMapper;

    @Autowired(required = false)
    ContactService contactService;

    @Autowired(required = false)
    RecycleService recycleService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public R moveToTrash(List<Integer> customerIds, String remark, List<Integer> delInfo) {
        R r=new R();
        //批量修改的客户状态至回收站
        for (Integer customerId : customerIds) {
            Customer customer =new Customer();
            customer.setCustomer_id(customerId);
            customer.setStatus(Constants.CUSTOMER_RECYCLE_STATUS);
            int result=customerMapper.updateCustomer(customer);
            if(result<=0) throw new CustomerException(customerId+"客户移入回收站失败");
            //移除客户用户对应关系
            int delResult=customerEmployeeMapper.delRelationshipByCustomerId(customerId);
            if(delResult<0) throw new CustomerException(customerId+"移除客户用户对应关系失败");

            //根据delInfo数组判断要删除的数据表，调用别人，联系人，跟单，订单等等。

            //转入回收站
            Recycle recycle=new Recycle();
            recycle.setCustomer_id(customer.getCustomer_id());
            //当前操作员
            Employee employee=new Employee();
            employee.setEmployee_id(7);

            recycle.setSalesman_id(employee.getEmployee_id());
            recycle.setDelete_date(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
            recycle.setDelete_reason(remark);
            recycleService.addRecycle(recycle);
        }
        r.setCode(200);
        r.setMsg(Constants.SUCCESS);
        return r;
    }

    /**
     * 从客户管理删除的客户移入公海
     * @param customerIds
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R moveToCustomerPoll(List<Integer> customerIds) {
        R r=new R();
        //批量修改客户状态至公海状态
        for (Integer customerId : customerIds) {
            Customer customer =new Customer();
            customer.setCustomer_id(customerId);
            customer.setStatus(Constants.CUSTOMER_POOL_STATUS);
            int result=customerMapper.updateCustomer(customer);
            if(result<=0) throw new CustomerException(customerId+"客户移入公海失败");

            //移除客户用户对应关系
            int delResult=customerEmployeeMapper.delRelationshipByCustomerId(customerId);
            if(delResult<0) throw new CustomerException(customerId+"移除客户用户对应关系失败");

            //转入公海
            Customer_Pool customer_pool=new Customer_Pool();
            customer_pool.setApplication_status(Constants.DEFAULT_APPLICATION_STATUS);//设置为默认状态
            customer_pool.setApplication_date(new Date());
            customer_pool.setCustomer(customer);
            Employee employee=new Employee();
            employee.setEmployee_id(0);
            customer_pool.setEmployee(employee);//转入公海后默认无申请业务员,故id为0
            int toPool =customerPoolMapper.insertCustomerPool(customer_pool);//将公海记录存到数据库
            if(toPool<=0) throw new CustomerException(customerId+"转入公海失败");
        }
        r.setCode(200);
        r.setMsg(Constants.SUCCESS);
        return r;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R modifyCustomer(Customer customer) {
        R r=new R();
        //修改客户信息

        int customerId=customerMapper.updateCustomer(customer);
        if(customerId<=0) throw new CustomerException("修改客户信息失败");

        //------------------后续会修改联系人信息，需要调用联系人相关mapper
        List<Contact> contacts=customer.getContact();
        if(contacts!=null && contacts.get(0)!=null){
            contactService.upDataContact(contacts.get(0));
        }


        //记录到客户操作表

        //当前系统操作业务员
        Employee employee=new Employee();
        employee.setEmployee_id(7);

        Customer_Records customer_records=new Customer_Records();
        customer_records.setUpdate_emp_id(employee.getEmployee_id());
        customer_records.setUpdate_date(new Date());
        customer_records.setCustomer_id(customer.getCustomer_id());
        int customerRecordsResult=customerRecordsMapper.updateRecords(customer_records);
        if(customerRecordsResult<=0) throw new CustomerException("修改客户日志记录失败");//操作失败则报出异常，触发回滚

        r.setCode(200);
        r.setMsg(Constants.SUCCESS);
        return r;
    }

    @Override
    public R getCustomerPage(PageRecv pageRecv) {
        R r=new R();
        List<Customer> customers=customerMapper.selectCustomerPageListWithOrder(pageRecv);
        List<Customer_Employee> customer_employees=new ArrayList();
        if(!customers.isEmpty()) {
            for (Customer customer : customers) {
                //装载客户记录
                //指定客户id的记录
                Customer_Records selectRecords = new Customer_Records();
                selectRecords.setCustomer_id(customer.getCustomer_id());
                //查询出指定客户的操作记录
                Customer_Records customer_records = customerRecordsMapper.selectRecords(selectRecords);
                //将查出的操作记录装载入客户
                customer.setCustomer_records(customer_records);


                //---------------------装载省市（暂时废弃）
                Province province = new Province();
                province.setProvince_d(0);
                province.setProvince_name("四川省");
                City city = new City();
                city.setCity_id(0);
                city.setCity_name("成都市");
                city.setProvince(province);
                customer.setCity(city);

                //---------------------等待装载联系人mapper
                List<Contact> contacts = contactMapper.queryContact(customer.getCustomer_id());
                if (contacts.isEmpty()) {
                    contacts.add(new Contact());//防止前端contacts字段为空
                }
                customer.setContact(contacts);

                //查询客户员工对应表
                Customer_Employee ceResult = new Customer_Employee();
                ceResult.setCustomer(customer);

                //装载业务员到对应关系中
                Employee empResult = customerEmployeeMapper.selectEmpByCustomer(ceResult);
                if (empResult == null) {
                    empResult = new Employee();//防止前端employee字段为空
                }
                ceResult.setEmployee(empResult);

                //统一装入customer_employees并返回
                customer_employees.add(ceResult);

            }
        }
        System.out.println(customers);
        r.setCode(200);
        r.setMsg(Constants.SUCCESS);
        PageResult pageResult=new PageResult();
        //设置总条数
        int count=customerMapper.countCustomerPageList(pageRecv);
        pageResult.setTotalSize(count);
        pageResult.setList(customer_employees);
        r.setData(pageResult);
        return r;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addCustomer(Customer customer) {
        R r=new R();
        //添加客户
        customer.setStatus(Constants.CUSTOMER_NORMAL_STATUS);
        int insertResult = customerMapper.insertCustomer(customer);//传入对象customer

        //添加默认联系人，姓名是客户本身
        Contact contact=customer.getContact().get(0);
        contact.setCustomer_id(customer.getCustomer_id());
        contact.setContact_name(customer.getCustomer_name());
        contactMapper.addContact(contact);

        //添加到客户员工对应关系
        Customer_Employee customer_employee=new Customer_Employee();
        if(insertResult<=0) throw new CustomerException("插入客户失败");//操作失败则报出异常，触发回滚

        //当前系统操作业务员
        Employee employee=new Employee();
        employee.setEmployee_id(7);
        customer_employee.setEmployee(employee);
        customer_employee.setCustomer(customer);

        int customerEmployeeResult=customerEmployeeMapper.insertRelationship(customer_employee);
        if(customerEmployeeResult<=0) throw new CustomerException("客户员工对应失败");//操作失败则报出异常，触发回滚

        //添加到客户记录表
        Customer_Records customer_records=new Customer_Records();
        customer_records.setCustomer_id(customer.getCustomer_id());
        customer_records.setUpdate_emp_id(employee.getEmployee_id());
        customer_records.setImport_emp_id(employee.getEmployee_id());
        customer_records.setImport_date(new Date());
        customer_records.setUpdate_date(new Date());
        int customerRecordsResult=customerRecordsMapper.insertRecords(customer_records);
        if(customerRecordsResult<=0) throw new CustomerException("客户日志记录失败");//操作失败则报出异常，触发回滚

        //若成功则返回成功结果
        r.setCode(200);
        r.setMsg(Constants.SUCCESS);
        return r;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R moveToOtherEmp(List<Integer> customerIds, Integer employeeId) {
        R r=new R();
        for (Integer customerId : customerIds) {
            //解除原客户与业务员的关系
            int delResult = customerEmployeeMapper.delRelationshipByCustomerId(customerId);
            if(delResult<0) throw new CustomerException("解除失败");//操作失败则报出异常，触发回滚
            //绑定新业务员
            Employee employee=new Employee();
            employee.setEmployee_id(employeeId);
            Customer customer=new Customer();
            customer.setCustomer_id(customerId);
            //建立关系
            Customer_Employee customer_employee=new Customer_Employee();
            customer_employee.setEmployee(employee);
            customer_employee.setCustomer(customer);
            //将关系存入数据库
            int customerEmployeeResult=customerEmployeeMapper.insertRelationship(customer_employee);
            if(customerEmployeeResult<=0) throw new CustomerException("客户员工对应失败");//操作失败则报出异常，触发回滚
        }
        //若成功则返回成功结果
        r.setCode(200);
        r.setMsg(Constants.SUCCESS);
        return r;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R modifyCustomerProtectedSetting(List<Integer> customerIds, Integer protectedSetting) {
        if(protectedSetting!=Constants.PROTECTED_DISABLE && protectedSetting!=Constants.PROTECTED_ENABLE){//判断保护期参数是否合法
            throw new CustomerException("保护期参数错误");
        }
        R r=new R();
        for (Integer customerId : customerIds) {
            Customer customer=new Customer();
            customer.setCustomer_id(customerId);
            customer.setEnable_protected(protectedSetting);
            int updateResult = customerMapper.updateCustomer(customer);
            if(updateResult<=0) throw new CustomerException("客户更新失败");
        }
        //若成功则返回成功结果
        r.setCode(200);
        r.setMsg(Constants.SUCCESS);
        return r;
    }

    @Override
    public R getCustomerCountByCondition(PageRecv pageRecv) {
        R r=new R();
        int count=customerMapper.countCustomerPageList(pageRecv);
        r.setCode(200);
        r.setMsg(Constants.SUCCESS);
        r.setData(count);
        return r;
    }

//    @Override
//    public R getCustomerCountByDate(Date startDate, Date endDate) {
////        System.out.println(cs);
//        return null;
//    }
}
